from django import forms
from django.contrib.auth.models import User
from CourseHub.models import Course, School, University, User, UserProfile, Comment
from django.contrib.auth.forms import UserCreationForm
import datetime

class RegisterForm(UserCreationForm):
    university = forms.ModelChoiceField(queryset = University.objects.all(), required=True)
    email = forms.EmailField(label = "Email")

    class Meta:
        model = User
        fields = ("username", "email", "university")

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            user = User.objects.get(email=email)
            raise forms.ValidationError("This email address already exists. Did you forget your password?")
        except User.DoesNotExist:
            return email

    def save(self, commit=True):
        new_user = super(UserCreationForm, self).save(commit=False)
        new_user.set_password(self.cleaned_data["password1"])
        if commit:
            new_user.save()
        new_userprofile = UserProfile(
            user=new_user, 
            university = University.objects.get(university_name = self.cleaned_data["university"]))
        new_userprofile.save()
        return new_user

class CreateCourseForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(CreateCourseForm, self).__init__(*args, **kwargs)
        self.fields['school'].queryset = School.objects.filter(university = University.objects.get(id = UserProfile.objects.get(user = user).university_id))
    class Meta:
        model = Course
        exclude = ('course_date', 'course_average')

RATING_CHOICES = (
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
)

class CreateCommentForm(forms.ModelForm):
    def __init__(self, course, *args, **kwargs):
        super(CreateCommentForm, self).__init__(*args, **kwargs)
        self.fields['course'].queryset = Course.objects.filter(id = course.id)

    course = forms.ModelChoiceField(queryset = Course.objects.all(),empty_label=None)
    comment_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=RATING_CHOICES)
    class Meta:
        model = Comment
        exclude = ('comment_date')

class SearchForm(forms.Form):
    university = forms.ModelChoiceField(queryset = University.objects.all(), required=False)
    course_title = forms.CharField(label = "course_title", max_length=50, required=False)
    course_code = forms.CharField(label = "course_code", max_length=20, required=False)
    course_subject = forms.CharField(label = "course_subject", max_length=20, required=False)